#!/usr/bin/env python
"""
PyLink-SR (Python Linked Software Radio System)
(c) Bob Cowdery (G3UKB) 2008

File: app_main.py
Date: July 2008

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

The author can be reached by email at

bob@g3ukb.co.uk

========================================================================
Module Description:

The startup application for the gui.

"""

#-----------------------------------------------------------------------
# System imports
import logging
import sys
import os
from time import sleep
import subprocess
from threading import Thread
import Pyro.core
from Pyro.EventService.Clients import Subscriber

# Set the PYTHONPATH
HOME = os.environ['PYLINK_HOME']
# Note that config_service.py and options.conf must live under $HOME/conf
sys.path.append(HOME + 'conf')
import config_service as config
config.open_config()
# Now we have the configuration loaded we can set the rest of PYTHONPATH
sys.path = sys.path + config.python_path().rsplit(',')
# ... before importing the rest of the modules
# Application imports
import logger_service as logger
import gtk_mini_gui as gui

#======================================================================
# The main class of 'a' gui application
class AppMainGui:
  def __init__(self):
    global glogger
    
    Pyro.config.PYRO_HOST = config.pyro_local_host()
      
    # Initialise the console components
    # Logging
    logger.init_logger()
    # Get our logger
    glogger = logging.getLogger('pylink.logger')
    
     # Get a hook into the event service
    self.es = Pyro.core.getProxyForURI("PYRONAME://"+Pyro.constants.EVENTSERVER_NAME)
    # The one and only GUI (at the moment)
    self.gui = gui.AppGui(self.es)
    # Start the event listener thread for GUI hints
    EventListener(self.gui).start()
    # Ask for hints as this is startup
    self.es.publish('ui_hints', ('do_hints', None))
    
  #-----------------------------------------------------------------------
  # Run the console, which is totally event driven from the GUI
  def run(self):
    global glogger
   
    # Start the GUI
    self.gui.main()
    # This only returns when the GUI is closed

#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
class UiHints(Subscriber):
    
    #---------------------------------------------------------------------------
    def __init__(self, gui):
        Subscriber.__init__(self)
        self.setThreading(0)
        self.gui = gui

    #---------------------------------------------------------------------------
    def event(self, event):
        # Wait for messages
        # Call the appropriate method on the GUI       
        #print 'Received UI Hint', event.msg
        func, args = event.msg
        if func == 'terminate':
          self.abort()
        elif func == 'do_hints':
          pass
        else:
          bound_func = getattr(self.gui, func)
          bound_func(args)

#------------------------------------------------------------------------------- 
class EventListener(Thread):
    
    #---------------------------------------------------------------------------
    def __init__(self, gui):
        Thread.__init__(self)
        self.gui = gui
    
    #---------------------------------------------------------------------------    
    def run(self):
        global glogger
        
        Pyro.core.initServer()
        listener = UiHints(self.gui)
        listener.subscribeMatch("ui_hints")
        glogger.info('PyLink-SR (GUI) listening..')
        listener.listen()
        glogger.info('PyLink-SR (GUI) listener exiting..')
        
#--------------------------------------------------------------------------
#
# Start from the command line
#
if __name__ == "__main__":
  global glogger
  
  app = AppMainGui()
  
  # Start the main loop
  glogger.info("PyLink-SR (GUI) running..")
  app.run()
  
  # Announce we are going 
  glogger.info("PyLink-SR (GUI) closing..")
  